class Solution(object):
    def nearestExit(self, maze, entrance):
        m = len(maze)
        n = len(maze[0])
        dist = 0
        entrance = tuple(entrance)
        al = set(entrance)
        now = {entrance}
        while now:
            next_set = set()
            for x, y in now:
                if x == 0 or x == m - 1 or y == 0 or y == n - 1:
                    if (x, y) != entrance:
                        return dist
                for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                    if 0 <= ux < m and 0 <= uy < n:
                        if (ux, uy) not in al and maze[ux][uy] == '.':
                            next_set.add((ux, uy))
                            al.add((ux, uy))
            now = next_set
            dist += 1
        return - 1



